package com.chentong.aop;

import java.lang.reflect.Proxy;

public abstract class Aspect {

    public void before(Object target, Object[] args) {
    }

    public void after(Object target, Object[] args) {
    }

    public void around(Object target, Object[] args) {
    }

    public void exception(Object target, Object[] args) {
    }

    public <T> T newInstance(Object target) {
        Object objectProxy = Proxy.newProxyInstance(Aspect.class.getClassLoader(), target.getClass().getInterfaces(), (proxy, method, args) -> {
            try {
                around(target, args);
                before(target, args);
                Object result = method.invoke(target, args);
                after(target, args);
                around(target, args);
                return proxy;
            } catch (Exception e) {
                e.printStackTrace();
                exception(target, args);
                return null;
            }
        });
        return (T) objectProxy;
    }
}
